/**
 * @工具类过滤器
 */
import Vue from 'vue';

/**
 * @显示刚刚 几天前 几分钟前 几月前 几年前
 * 调用演示 {{ 值 | infoatime}}
 * */

Vue.filter('infoatime', function (time) {
  var ago, curTime, diff, int;
  let info = function (time) {
    time -= 0;
    if (('' + time).length === 10) {
      time *= 1000;
    }
    return time;
  };
  time = info(time);
  int = parseInt;
  curTime = +new Date();
  diff = curTime - time;
  ago = '';
  if (1000 * 60 > diff) {
    ago = '刚刚';
  } else if (1000 * 60 <= diff && 1000 * 60 * 60 > diff) {
    ago = int(diff / (1000 * 60)) + '分钟前';
  } else if (1000 * 60 * 60 <= diff && 1000 * 60 * 60 * 24 > diff) {
    ago = int(diff / (1000 * 60 * 60)) + '小时前';
  } else if (1000 * 60 * 60 * 24 <= diff && 1000 * 60 * 60 * 24 * 30 > diff) {
    ago = int(diff / (1000 * 60 * 60 * 24)) + '天前';
  } else if (1000 * 60 * 60 * 24 * 30 <= diff && 1000 * 60 * 60 * 24 * 30 * 12 > diff) {
    ago = int(diff / (1000 * 60 * 60 * 24 * 30)) + '月前';
  } else {
    ago = int(diff / (1000 * 60 * 60 * 24 * 30 * 12)) + '年前';
  }
  return ago;
});

/**
 * @格式化日期
 * 调用演示 {{值 | dataFormat(yyyy-MM-dd)}} 显示'2012-11-22'
 * ******  {{值 | dataFormat}} 显示'2012-11-22 13:21:23'
 * */
Vue.filter('dataFormat', function (originVal, info) {
  const dt = new Date(originVal * 1000);
  const y = dt.getFullYear();
  const m = (dt.getMonth() + 1 + '').padStart(2, '0');
  const d = (dt.getDate() + '').padStart(2, '0');
  const hh = (dt.getHours() + '').padStart(2, '0');
  const mm = (dt.getMinutes() + '').padStart(2, '0');
  const ss = (dt.getSeconds() + '').padStart(2, '0');
  return info ? `${y}-${m}-${d}` : `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
});

/**
 * @js数组去重这里我提供filter方法来完成
 * 需要传递去重的值过来,记住是值不是一整个数组！！！
 * */
Vue.prototype.$DuplicateRemoval = function (e) {
  if (e.length > 0) {
    e = e.filter((res, index) => {
      return e.indexOf(res) === index;
    });
    return e;
  } else {
    console.error('你可能没有搞明白去重的意义');
  }
  // 方法二(需要就释放)
  // return Array.from(new set(e));
};